<?php
namespace Leaps\Config;
use Leaps\Filesystem\Filesystem;
class FileLoader implements LoaderInterface
{

    /**
     * 文件系统实例
     *
     * @var \Leaps\Filesystem\Filesystem
     */
    protected $files;

    /**
     * 默认的配置路径
     *
     * @var string
     */
    protected $defaultPath;

    /**
     * 缓存名称空间和组是否存在
     *
     * @var array
     */
    protected $exists = array ();

    /**
     * 创建一个新文件配置加载程序
     *
     * @param \Leaps\Filesystem\Filesystem $files
     * @param string $defaultPath
     * @return void
     */
    public function __construct(Filesystem $files, $defaultPath)
    {
        $this->files = $files;
        $this->defaultPath = $defaultPath;
    }

    /**
     * 加载配置组。
     *
     * @param string $environment
     * @param string $group
     * @param string $namespace
     * @return array
     */
    public function load($group)
    {
        $items = array ();
        if ( is_null ( $this->defaultPath ) ) {
            return $items;
        }
        $file = "{$this->defaultPath}/{$group}.php";
        if ( $this->files->exists ( $file ) ) {
            $items = $this->files->getRequire ( $file );
        }
        $file = "{$this->defaultPath}/".LEAPS_ENV."/{$group}.php";
        if ( $this->files->exists ( $file ) ) {
            $items = $this->mergeEnvironment ( $items, $file );
        }
        return $items;
    }

    /**
     * 合并配置到items.
     *
     * @param array $items
     * @param string $file
     * @return array
     */
    protected function mergeEnvironment(array $items, $file)
    {
        return array_replace_recursive ( $items, $this->files->getRequire ( $file ) );
    }

    /**
     * 判断组是否存在
     *
     * @param string $group
     * @param string $namespace
     * @return bool
     */
    public function exists($group)
    {
        if ( isset ( $this->exists [$group] ) ) {
            return $this->exists [$group];
        }
        if ( is_null ( $this->defaultPath ) ) {
            return $this->exists [$group] = false;
        }
        $file = "{$this->defaultPath}/{$group}.php";
        $exists = $this->files->exists ( $file );
        return $this->exists [$group] = $exists;
    }

    /**
     * 获取文件内容
     *
     * @param string $path
     * @return mixed
     */
    protected function getRequire($path)
    {
        return $this->files->getRequire ( $path );
    }

    /**
     * 获取文件系统实例
     *
     * @return \Leaps\Filesystem\Filesystem
     */
    public function getFilesystem()
    {
        return $this->files;
    }
}
